(use-package ess-site
  :init
  (modify-coding-system-alist 'file "\\.log\\'\\|\\.lst\\'\\|\\.sas\\'" 'chinese-gb18030)
  (defun p1uxtar-SAS-goto-sas ()
    (interactive)
    (find-file
     (concat
      (dired-replace-in-string "Log" "Program"
                               (file-name-sans-extension (buffer-file-name)))
      ".sas")))
  (defun p1uxtar-SAS-goto-log ()
    (interactive)
    (find-file
     (concat
      (dired-replace-in-string "Program" "Log"
                               (file-name-sans-extension (buffer-file-name)))
      ".log")))
  (defun p1uxtar-SAS-semicolon ()
    (interactive)
    (progn
      (sas-indent-line)
      (mwim-end-of-code)
      (insert ";")))
  (defun p1uxtar-copy-kf-2-ch ()
    (interactive)
    (thing-copy-whole-buffer)
    (let* ((cfile (expand-file-name (buffer-file-name)))
           (cpath (nth 1 (reverse (split-string cfile "/"))))
           (dfile (file-name-nondirectory (buffer-file-name))))
      (when (string= "KF" cpath)
        (let* ((dpath "../CH/"))
          (find-file (concat dpath dfile))
          (erase-buffer)
          (yank)
          (goto-char (point-min))
          (while (search-forward "kf" nil t)
            (replace-match "ch"))
          (find-file cfile)))))
  (defun p1uxtar-SAS-vvalue ()
    "Get the formatted value that the variable under cursor."
    (interactive)
    (let ((symbol (thing-at-point 'symbol)))
      (when symbol (kill-new symbol)))
    (let ((beg (progn (skip-syntax-backward "^ " (line-beginning-position))
                      (point)))
          (end (progn (skip-syntax-forward "^ " (line-end-position))
                      (point))))
      (awesome-pair-wrap-round)
      (goto-char beg)
      (ess-yank)
      (insert "_v=vvalue")
      ;; (goto-char (+ end (- end beg)))
      (search-forward ")")
      (insert ";")
      (newline-and-indent)))
  (defun p1uxtar-SAS-vvalue ()
    "Get the formatted value that the variable under cursor."
    (interactive)
    (let (pt)
      (skip-chars-backward "-_A-Za-z0-9")
      (setq pt (point))
      (skip-chars-forward "-_A-Za-z0-9")
      (set-mark pt))
    (thing-copy-region-or-line)
    (insert "_v=vvalue();\n")
    (backward-char 3)
    (ess-yank)
    (forward-line)
    (mwim-beginning-of-code-or-line))
  (add-hook 'SAS-mode-hook
            (lambda ()
              (local-set-key (kbd "C-c v") 'p1uxtar-SAS-vvalue)
              (local-set-key (kbd "<f5>") 'p1uxtar-SAS-goto-sas)
              (local-set-key (kbd "<f6>") 'p1uxtar-SAS-goto-log))))

(require '+cdisc-mode)
